package com.ys.controller.api.purchase;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ys.service.flow.YspTaskService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgInvoiceRegist;
import com.ys.entity.purchase.TcgInvoiceRegistItem;
import com.ys.entity.purchase.TcgPurchaseAppointOrderProductComponent;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.purchase.TcgInvoiceRegistService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/*
 * 发票登记单
 */
@Controller
@RequestMapping("/api/inter/tcgInvoiceRegist")
public class ApiInterTcgInvoiceRegistController {
	
	@Autowired
	private CommonApiService<TcgInvoiceRegistItem> commonApiService;
	@Autowired
	private TcgInvoiceRegistService tcgInvoiceRegistService;

	@Autowired
	private YspTaskService yspTaskService;

	@RequiresPermissions("tcgInvoiceRegist:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcgInvoiceRegistItem cond, String conditions){
		
		cond = setSeachSql(cond, conditions);
	
		return commonApiService.searchLay(cond);
	}
	
	/**
	 * 新增
	 */
	@RequestMapping("/add")
	@ResponseBody
	@RequiresPermissions("tcgInvoiceRegist:add")
	public R add(String bid, String bidInvoiceOffset, String remark, String invoiceNo, String invoiceDay,
			BigDecimal taxPercent, BigDecimal amountNoTax, BigDecimal tax, BigDecimal amountWithTax, String subData) {
		try {
			return tcgInvoiceRegistService.add(bid, bidInvoiceOffset, remark, invoiceNo, invoiceDay, taxPercent, amountNoTax, tax, amountWithTax, subData, MenuId.TCG_InvoiceRegist);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/edit")
	@ResponseBody
	@RequiresPermissions("tcgInvoiceRegist:add")
	public R edit(String bid, String bidInvoiceOffset, String remark, String invoiceNo, String invoiceDay,
			BigDecimal taxPercent, BigDecimal amountNoTax, BigDecimal tax, BigDecimal amountWithTax, String subData) {
		try {
			return tcgInvoiceRegistService.edit(bid, bidInvoiceOffset, remark, invoiceNo, invoiceDay, taxPercent, amountNoTax, tax, amountWithTax, subData, MenuId.TCG_InvoiceRegist);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/**
	 * 流转通过
	 */
	@RequiresPermissions("tcgInvoiceRegist:add")
	@PostMapping("/flowPass")
    @ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		TcgInvoiceRegist tcgInvoiceRegist = new TcgInvoiceRegist().setId(id).queryFirst();
		try {
    		String loginUserId = ShiroUtils.getUserId();
			return tcgInvoiceRegistService.flowPass(tcgInvoiceRegist.getBid(), loginUserId);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcgInvoiceRegist:add")
	@PostMapping("/flowRefuse")
    @ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){
		TcgInvoiceRegist tcgInvoiceRegist = new TcgInvoiceRegist().setId(id).queryFirst();
		try {
			return tcgInvoiceRegistService.flowRefuse(tcgInvoiceRegist.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcgInvoiceRegist:add")
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){
		TcgInvoiceRegist tcgInvoiceRegist = new TcgInvoiceRegist().setId(id).queryFirst();
		try {
			return yspTaskService.flowInit(tcgInvoiceRegist.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	
	/**
	 * 删除
	 * @throws Exception 
	 */
	@PostMapping("/delete")
    @ResponseBody
	public R delete(Long id){
		
		try {
			return tcgInvoiceRegistService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("操作失败，请联系客服");
		}
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("tcgInvoiceRegist:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgInvoiceRegistItem cond, String conditions) throws Exception{
		
		cond = setSeachSql(cond, conditions);
		
		cond.setOrderby("A.Id DESC");
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCG_PurchaseAppointOrder2)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
    	
        ExportExcelUtils<TcgPurchaseAppointOrderProductComponent> util = new ExportExcelUtils<TcgPurchaseAppointOrderProductComponent>(new TcgPurchaseAppointOrderProductComponent());
        
        String toFilePath = util.exportExcel(listData, listField, "预约采购管理");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcgInvoiceRegistItem setSeachSql(TcgInvoiceRegistItem cond, String conditions){
    	
    	cond.addLeftJoin("TCG_InvoiceRegist B ON B.Bid = A.Pbid")
    	.addField("B.Bid bid")
    	.addField("B.AnnexFile annexFile")
    	.addField("B.Remark remark")
    	.addField("B.InvoiceNo invoiceNo")
    	.addField("B.InvoiceDay invoiceDay")
    	.addField("B.TaxPercent taxPercent")
    	.addField("B.AmountNoTax amountNoTax")
    	.addField("B.Tax tax")
    	.addField("B.AmountWithTax amountWithTax")
		.addField("B.EffectStock effectStock")
    	
    	.addLeftJoin("TS_UserChange C ON C.Id = B.CreateChangeId")
    	.addField("CONCAT(C.UserId, '/', C.UserName) createUser")
    	
    	.addLeftJoin("TCG_InvoiceOffsetItem AA ON AA.Id = A.InvoiceOffsetItemId")
    	.addField("AA.OffsetAmount offsetAmount")
    	
    	.addLeftJoin("TCG_InvoiceOffset BB ON BB.Id = B.InvoiceOffsetId")
    	.addField("BB.Bid bidInvoiceOffset")
    	.addField("BB.SourceAddress sourceAddress")
    	.addField("BB.OffsetTotalAmount offsetTotalAmount")
    	
    	
    	.addLeftJoin("TB_CompanyInfo CC ON CC.Vid = BB.CompanyVid")
    	.addField("CC.Vid companyVid")
    	.addField("CC.Vname companyVname")
    	.addField("CC.Tax companyTax")
    	
    	.addLeftJoin("TCW_PartnerBankInfo DD ON DD.Id = BB.PartnerBankInfoId")
    	.addField("DD.PartnerName partnerName")
    	.addField("DD.Vgssh partnerVgssh")
    	
		.addLeftJoin("YS_ProcInst B99 ON B99.Bid = B.Bid")
		.addField("B99.UpdateTime auditTime");

		String _ys_invoiceDayBegin = ConditionUtil.getConditionValue(conditions, "_ys_invoiceDayBegin");
		String _ys_invoiceDayEnd = ConditionUtil.getConditionValue(conditions, "_ys_invoiceDayEnd");
		if (_ys_invoiceDayBegin != null && _ys_invoiceDayBegin.length() > 0) {
			cond.where("B.InvoiceDay >= '" + _ys_invoiceDayBegin + "'");
		}
		if (_ys_invoiceDayEnd != null && _ys_invoiceDayEnd.length() > 0) {
			cond.where("B.InvoiceDay <= '" + _ys_invoiceDayEnd + "'");
		}
		
        return  cond;
    }
}
